/* eslint-disable react/display-name */
import React, { forwardRef, useEffect, useImperativeHandle, useRef } from 'react';
import { useBoolean, useEventListener, useFullscreen, useHover, useTimeout, useCreation } from 'ahooks';
import RenderJudge from '@/components/RenderJudge';
import Provider from './components/Provider';
import Loading from './components/Loading';
import { Context, useStores } from './utils/store';
import styles from './style/index.module.scss';
import Controller from './components/Controller'
import { liveUrlTransformToArray } from '@/common/tool';
import CountDown from "./components/CountDown"
import Livelier from './components/Liveover'

const Main = forwardRef(({ ctrl, matchTime, data, isLive, mobile }, ref) => {
  const { status, methods } = useStores();
  useImperativeHandle(ref, () => ({
    create: methods.create,
    destroy: methods.destroy,
  }));

  const Ctrl = useCreation(() => status.create ? ctrl : <></>, [status.create])
  return (
    <>
      {Ctrl}
      {/* <RenderJudge
        value={status.played && instance && status.bufferLoading}
        active={(<BufferLoading />)}
      /> */}
      <CountDown matchTime={matchTime} isLive={isLive} mobile={mobile}></CountDown>
      {/* <RenderJudge
        value={status.loading}
        active={(<Loading />)}
      /> */}
      <Livelier data={data} isLive={isLive} mobile={mobile}></Livelier>
    </>
  );
});

const LivePlayer = forwardRef(({ data, ctrl, volume, children, videoBackList, matchTime, mobile }, ref) => {
  const isLive = !videoBackList || !videoBackList?.length
  const liveData = liveUrlTransformToArray(data)
  const containerRef = useRef();
  const [ctrlVisible, { setFalse: setCtrlHidden, setTrue: setCtrlDisplay }] = useBoolean(false);

  useHover(containerRef, {
    onEnter: setCtrlDisplay,
    onLeave: setCtrlHidden,
  });

  const [fullScreen, { enterFullscreen: setFull, exitFullscreen: exitFull }] = useFullscreen(containerRef);

  // 倒计时隐藏控制器
  useEventListener('mousemove', setCtrlDisplay, { target: containerRef });

  const methods = {
    // 全屏
    fullScreen: setFull,
    // 退出全屏
    exitScreen: exitFull,
  };

  const status = {
    fullScreen,
    ctrlVisible,
    mobile
  };

  // 全屏倒计时隐藏控制器
  useTimeout(setCtrlHidden, ctrlVisible && fullScreen ? 3000 : undefined);


  return (

    <div ref={containerRef} className={styles.container}>
      <Provider data={liveData} status={status} methods={methods} volume={volume} videoBackList={videoBackList}>
        <Main ref={ref} ctrl={ctrl} matchTime={matchTime} data={liveData} isLive={isLive} mobile={mobile} />
        {children}
      </Provider>

    </div>
  );
});

LivePlayer.defaultProps = {
  data: [],
  ctrl: (<Controller />),
  mobile: false
};

LivePlayer.Controller = Controller;
LivePlayer.Context = Context;
LivePlayer.useStores = useStores;

export default LivePlayer;
